<?php

namespace TpAmis\Traits;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use TpAmis\Renderers\AjaxAction;
use TpAmis\Renderers\Button;
use TpAmis\Renderers\DialogAction;
use TpAmis\Renderers\OtherAction;
use TpAmis\Renderers\Service;

trait ButtonsTrait
{

    /**
     * 操作列
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     *
     * @return \TpAmis\Renderers\Operation
     */
    protected function rowActions($dialog = false, string $dialogSize = 'md')
    {
        if (is_array($dialog)) {
            return amis()->Operation()->label('操作')->buttons($dialog);
        }

        $actions = amis()->Operation()->label('操作')->buttons([
            $this->rowShowButton($dialog, $dialogSize),
            $this->rowEditButton($dialog, $dialogSize),
            $this->rowDeleteButton(),
        ]);

        return $actions;
    }

    /**
     * 返回列表按钮
     */
    protected function backButton(): OtherAction
    {
        return amis()->OtherAction()
            ->label('返回')
            ->icon('fa-solid fa-chevron-left')
            ->level('primary')
            ->onClick('window.history.back();');
    }

    public function LinkButton($title, $url, $icon = '', $level = '')
    {
        $title  = $title ?: '链接';
        $action = $this->customButton($title, 'LinkAction', $icon, $level);
        $action->link($url);

        if (! authAmis($action)) {
            return $action->disabled(true);
        }
        return $action;
    }
    public function UrlButton($title, $url, $blank = true, $icon = '', $level = 'link')
    {
        $title  = $title ?: '链接';
        $action = $this->customButton($title, 'UrlAction', $icon, $level);
        $action->url($url)->blank($blank);
        if (! authAmis($action)) {
            return $action->disabled(true);
        }
        return $action;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function AjaxFormButton(string $title = '', string $url = '', string $method = 'get', array $args = [], array $options = []): AjaxAction
    {
        return $this->AjaxButton($title, $url, $method, $args, $options);
    }

    /**
     * ajax按钮
     * @param string $title
     * @param string $url
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function DialogAjaxButton(string $title = '', string $url = '', string $method = 'get', array $args = [], array $data = [], array $options = [])
    {
        isset($args[$this->primaryKey]) ?: $args[$this->primaryKey] = '${' . $this->primaryKey . '}';

        $bottonAction = amis()->AjaxAction()->label($title)->close(true)->primary(true)->api($this->amisBaseApi($url, $method, [$args], $data))
            ->feedback(['title' => '提示:', 'body' => '操作成功', 'actions' => [["type" => "button", "actionType" => "close", "label" => "关闭"]]]);

        $action = amis()->DialogAction()->label($title)->dialog(
            amis()->Dialog()->body(amis()->Form())->title('确认是否' . $title)
                ->actions([$bottonAction])
        );

        foreach ($options as $key => $option) {
            //添加自定义参数，
            $action->$key($option);
        }
        if (! authAmis($action)) {
            $action->disabled();
        }
        return $action;
    }
    /**
     * ajax按钮
     * @param string $title
     * @param string $url
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function AjaxButton(string $title = '', string $url = '', string $method = 'get', array $args = [], array $data = [], array $options = []): AjaxAction
    {
        isset($args[$this->primaryKey]) ?: $args[$this->primaryKey] = '${' . $this->primaryKey . '}';

        $action = amis()->AjaxAction()->label($title);

        $action->api($this->amisBaseApi($url, $method, [$args], $data));
        foreach ($options as $key => $option) {
            //添加自定义参数，
            $action->$key($option);
        }
        if (! authAmis($action)) {
            $action->disabled();
        }
        return $action;
    }

    /**
     * 行自定义按钮
     *
     * @param string $title 弹窗标题 & 按钮文字, 默认: 新增
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function rowCustomButton(string $title = '', string $ActionName = '', $icon = '', $level = 'link')
    {
        $title = $title ?: '自定义按钮';

        $action = amis()->$ActionName()->label($title);
        $action->label($title)->icon($icon)->level($level);

        return $action;
    }
    /**
     * 新增按钮
     *
     * @param  $dialog     是否弹窗, 弹窗: true|dialog, 抽屉: drawer,
     * @param string $title 弹窗标题 & 按钮文字, 默认: 新增
     *
     * @return \TpAmis\Renderers\DialogAction|\TpAmis\Renderers\LinkAction
     */
    protected function customButton(string $title = '', string $ActionName = '', $icon = '', $level = 'primary')
    {
        $title = $title ?: '自定义按钮';

        $action = amis()->$ActionName()->label($title);
        $action->label($title)->icon($icon)->level($level);

        return $action;
    }

    /**
     * 行编辑按钮
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @return DialogAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function detailButton(string $title = '详情', string $dialogSize = 'full'): DialogAction
    {
        $IFrame = amis()->IFrame()->src(adminUrl('detail', [$this->primaryKey => '${' . $this->primaryKey . '}'], true, true));
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($IFrame)->size($dialogSize)->actions([])
        );

        $action->label($title)->level('success');
        if (! authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }
    /**
     * 添加按钮
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @return DialogAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function createButton(string $title = '添加', string $dialogSize = 'full'): DialogAction
    {
        $baseApi = adminUrl('create', [$this->primaryKey => '${' . $this->primaryKey . '}'], true, true);

        $IFrame = amis()->IFrame()->src($baseApi);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($IFrame)->size($dialogSize)->actions([])
        );

        $action->label($title)->level('success');
        if (! authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }
    /**
     * 添加按钮
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @return DialogAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function addButton(string $title = '添加', string $dialogSize = 'full'): DialogAction
    {
        $baseApi = BaseApiGet('add', [$this->primaryKey => '${' . $this->primaryKey . '}']);

        $urlPage = amis()->Service()->schemaApi($baseApi);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($urlPage)->size($dialogSize)->actions([])
        );


        $action->label($title)->level('success');
        if (! authAmis($action)) {
            return $action->disabled();
        }
        return $action;
    }
    /**
     * 行编辑按钮
     *
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     *
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function rowEditButton(string $title = '编辑', string $dialogSize = 'full'): DialogAction
    {
        $IFrame = amis()->IFrame()->src($this->adminUrl('edit', [$this->primaryKey => '${' . $this->primaryKey . '}']));
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($IFrame)->size($dialogSize)->actions([])
        );

        $action->label($title);
        if (! authAmis($action)) {
            $action->disabled();
        }
        return $action;
    }
  /**
     * 行编辑按钮
     *
     * @param string $title 弹窗标题 & 按钮文字, 默认: 编辑
     *
     * @param string $dialogSize 弹窗大小, 默认: md, 可选值: xs | sm | md | lg | xl | full
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function rowEditerButton(string $title = '编辑', string $dialogSize = 'full'): DialogAction
    {
        $baseApi = BaseApiGet('editer', [$this->primaryKey => '${' . $this->primaryKey . '}']);

        $urlPage = amis()->Service()->schemaApi($baseApi);
        $action = amis()->DialogAction()->dialog(
            amis()->Dialog()->title($title)->body($urlPage)->size($dialogSize)->actions([])
        );
         
        $action->label($title);
        if (! authAmis($action)) {
            $action->disabled();
        }
        return $action;
    }

    /**
     * 行删除按钮
     *
     * @param string $title
     * @param string $url
     * @return DialogAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function rowDeleteButton(string $title = '删除', array $args = ['id' => '${id|raw}'], array $options = []): AjaxAction
    {
        return $this->statusButton($title, 'modify', 'delete', $args, $options);
    }


    protected string $exportApi = 'export';


    /**
     * 行启用按钮
     *
     * @param string $title
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function rowEnableButton(string $title = '启用', array $args = ['id' => '${id|raw}'], $data = ['status' => 1], array $options = []): AjaxAction
    {
        return $this->statusButton($title, 'modify', 'post', $args, $data, $options);
    }


    /**
     * 行禁用按钮
     *
     * @param string $title
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function rowDisableButton(string $title = '禁用', array $args = ['id' => '${id|raw}'], $data = ['status' => 0], array $options = []): AjaxAction
    {

        return $this->statusButton($title, 'modify', 'post', $args, $data, $options);
    }

    /**
     * 批量启用按钮
     *
     * @param string $title
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function bulkEnableButton(string $title = '启用', array $args = ['id' => '${ids|raw}'], $data = ['status' => 1], array $options = []): AjaxAction
    {
        return $this->statusButton($title, 'modify', 'post', $args, $data, $options);
    }


    /**
     * 批量禁用按钮
     *
     * @param string $title
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function bulkDisableButton(string $title = '禁用', array $args = ['id' => '${ids|raw}'], $data = ['status' => 0], array $options = []): AjaxAction
    {

        return $this->statusButton($title, 'modify', 'post', $args, $data, $options);
    }

    /**
     * 行状态开关按钮
     *
     * @param string $title
     * @param string $url
     * @param string $method
     * @param array $args
     * @param array $options
     * @return AjaxAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function statusButton(string $title = '', string $url = 'modify', string $method = 'post', array $args = [], array $data = [], array $options = []): AjaxAction
    {
        // isset($args['primaryKey']) ?$args: $args[$this->primaryKey] = '${' . $this->primaryKey . '}';
        $action = $this->AjaxButton($title, $url, $method, $args, $data, $options)->confirmText('确认' . $title . '？');

        if (! authAmis($action)) {
            $action->disabled();
        }
        return $action;
    }


    /**
     * @param string $url
     * @return DialogAction
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected function bulkDeleteButton(string $title = '删除', string $method = 'delete', array $args = ['id' => '${ids|raw}', 'status' => 0], array $options = []): AjaxAction
    {

        return $this->statusButton($title, 'modify', $method, $args, $options);
    }

    /**
     * 导出按钮
     *
     * @param bool $disableSelectedItem
     *
     * @return \TpAmis\Renderers\Service
     */
    protected function exportAction($disableSelectedItem = false)
    {
        // 获取主键名称
        $primaryKey = $this->primaryKey();
        // 下载路径
        $downloadPath = adminUrl('_download_export');
        // 导出接口地址
        $exportPath = BaseApiPost('export');
        // 无数据提示
        $pageNoData = '无数据提示';
        // 选中行无数据提示
        $selectedNoData = '选中行无数据';
        // 按钮点击事件
        // $event = fn($script) => ['click' => ['actions' => [['actionType' => 'custom', 'script' => $script]]]];
        $event = function ($script) {
            return [
                'click' => [
                    'actions' => [
                        ['actionType' => 'custom', 'script' => $script]
                    ]
                ]
            ];
        };
        // 导出处理动作
        $doAction = "doAction([{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:true}}},{actionType:'ajax',args:{api:{url:url.toString(),method:'get'}}},{actionType:'setValue',componentId:'export-action',args:{value:{showExportLoading:false}}},{actionType:'custom',expression:'\${event.data.responseResult.responseStatus===0}',script:'window.open(\'{$downloadPath}?path=\'+event.data.responseResult.responseData.path)'}])";
        // 按钮
        $buttons = [
            // 导出全部
            amis()->VanillaAction()->label('导出全部')->onEvent(
                $event("let data=event.data;let params=Object.keys(data).filter(key=>key!=='page' && key!=='__super').reduce((obj,key)=>{obj[key]=data[key];return obj;},{});let url=new URL('{$exportPath}',window.location.origin);Object.keys(params).forEach(key=>url.searchParams.append(key,params[key]));{$doAction}")
            ),
            // 导出本页
            amis()->VanillaAction()->label('导出本页')->onEvent(
                $event("let ids=event.data.items.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$pageNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('_ids',ids.join(','));{$doAction}")
            ),
        ];
        // 导出选中项
        if (! $disableSelectedItem) {
            $buttons[] = amis()->VanillaAction()->label('导出选中项')->onEvent(
                $event("let ids=event.data.selectedItems.map(item=>item.{$primaryKey});if(ids.length===0){return doAction({actionType:'toast',args:{msgType:'warning',msg:'{$selectedNoData}'}})};let url=new URL('{$exportPath}',window.location.origin);url.searchParams.append('_ids',ids.join(','));{$doAction}")
            );
        }

        $action = amis()->Service()
            ->id('export-action')
            ->set('align', 'right')
            ->set('data', ['showExportLoading' => false])
            ->body(
                amis()->Spinner()->set('showOn', '${showExportLoading}')->overlay()->body(
                    amis()->DropdownButton()
                        ->label('导出标题')
                        ->set('icon', 'fa-solid fa-download')
                        ->buttons($buttons)
                        ->closeOnClick()
                        ->align('right')
                )
            );
        if (! authAmis($action)) {
            return $action->disabled(true);
        }
        return $action;
    }
}
